<?php

namespace api\admin;

use utils\base64_to_file;
use utils\zip;

class active_person
{
    //添加
    public function add($data)
    {
        $user = $data['user'];
        $travel = $data['travel'];
        $hotel = $data['hotel'];
        $trip_active = $data['trip_active'];
        $trip_eat = $data['trip_eat'];
        $driver = $data['driver'];
        $contact = $data['contact'];
        $remark = $data['remark'];
        $active_id = (int)$data['active']['id'];
        $active = $data['active_text'];
        $eat = $data['eat_text'];
        $time = time();

        $con = con();

        //插入历史嘉宾信息
        $class = $user['class'];
        $org = $user['org'];
        $name = $user['name'];
        $sex = $user['sex'];
        $nation = $user['nation'];
        $job = $user['job'];
        $phone = $user['phone'];
        $num = mysqli_query($con, "select * from guest where name='$name' and class='$class' and org='$org'");
        $num = mysqli_fetch_all($num, true);
        if (count($num) === 0) {//不存在，则执行插入
            mysqli_query($con, "insert into guest(class,org,name,sex,nation,job,phone,create_time,update_time) values('$class','$org','$name','$sex','$nation','$job','$phone',$time,$time )");
            $guest_id = mysqli_insert_id($con);
        } else {//存在，则拿去id
            $guest_id = (int)$num[0]['id'];
        }

        //插入活动人员明细信息
        $start_type = $travel['start_type'];
        if (empty($travel['start_time'])) {
            $start_time = 0;
        } else {
            $start_time = strtotime($travel['start_time']);
        }
        $end_type = $travel['end_type'];
        if (empty($travel['end_time'])) {
            $end_time = 0;
        } else {
            $end_time = strtotime($travel['end_time']);
        }
        $hotel_name = $hotel['hotel_name'];
        $hotel_room_type = $hotel['hotel_room_type'];
        $hotel_room = $hotel['hotel_room'];
        $driver_name = $driver['driver_name'];
        $car_no = $driver['car_no'];
        $car_officer = $driver['car_officer'];
        $leader_root = $contact['leader_root'];
        $leader_org = $contact['leader_org'];
        $worker = $contact['worker'];
        $remark = $remark['remark'];


        $res = mysqli_query($con, "insert into active_person(active_id,guest_id,start_type,start_time,end_type,end_time,hotel_name,hotel_room_type,hotel_room,driver_name,car_no,car_officer,leader_root,leader_org,worker,create_time,update_time,remark,active,eat) 
                                                        values($active_id,$guest_id,'$start_type',$start_time,'$end_type',$end_time,'$hotel_name','$hotel_room_type','$hotel_room','$driver_name','$car_no','$car_officer','$leader_root','$leader_org','$worker',$time,$time,'$remark','$active','$eat')");
        mysqli_close($con);
        if ($res) {
            return out_right('添加成功！');
        } else {
            return out_error('添加失败！');
        }

//        //插入行程信息
//        $active_person_id = mysqli_insert_id($con);
//        $sql0 = "insert into active_person_trip(active_person_id,type,content,start_time,end_time,create_time,update_time) values";
//        if (!empty($trip_active)) {
//            $a = [];
//            for ($i = 0; $i < count($trip_active); $i++) {
//                $content = $trip_active[$i]['content'];
//                $start_time = strtotime($trip_active[$i]['start_time']);
//                $end_time = strtotime($trip_active[$i]['end_time']);
//                $a[] = "($active_person_id,1,'$content',$start_time,$end_time,$time,$time)";
//            }
//            $sql = $sql0 . implode(',', $a);
//            $res_trip_active = (bool)mysqli_query($con, $sql);
//        } else {
//            $res_trip_active = true;
//        }
//
//        if (!empty($trip_eat)) {
//            $a = [];
//            for ($i = 0; $i < count($trip_eat); $i++) {
//                $content = $trip_eat[$i]['content'];
//                $start_time = strtotime($trip_eat[$i]['start_time']);
//                $end_time = strtotime($trip_eat[$i]['end_time']);
//                $a[] = "($active_person_id,2,'$content',$start_time,$end_time,$time,$time)";
//            }
//            $sql = $sql0 . implode(',', $a);
//            $res_trip_eat = (bool)mysqli_query($con, $sql);
//        } else {
//            $res_trip_eat = true;
//        }

    }

    //修改
    public function edit($data)
    {
        $id = (int)$data['id'];
        $time = time();
        $name = $data['name'];
        $phone = $data['phone'];
        $remark = $data['remark'];

        $con = con();
        $res = mysqli_query($con, "update active_person set name='$name',phone='$phone',remark='$remark',update_time=$time where id=$id");
        mysqli_close($con);
        if ($res) {
            return out_right('修改成功！');
        } else {
            return out_error('修改失败！');
        }
    }

    //删除
    public function del($data)
    {
        $id = (int)$data['id'];
        $time = time();
        $con = con();
        $res = mysqli_query($con, "update active_person set is_delete=0,delete_time=$time where id=$id");
        mysqli_close($con);
        if ($res) {
            return out_right('删除成功！');
        } else {
            return out_error('删除失败！');
        }
    }

    //获取分页列表
    public function getList($data)
    {
        $name = $data['name'];
        $page = (int)$data['page'];
        $size = (int)$data['size'];
        $start = ($page - 1) * $size;

        $con = con();
        $where = " where a.is_delete=1 ";
        if (!empty($name)) {
            $where .= " and b.name like '%$name%'";
        }
        $limit = " order by a.`id` desc limit $start,$size";
        $sql = "select a.*,b.class,b.org,b.name,b.sex,b.nation,b.job,b.phone from active_person a left join guest b on (a.guest_id=b.id) $where";
        $data = mysqli_query($con, $sql . $limit);
        $data = mysqli_fetch_all($data, true);
        $total = mysqli_query($con, $sql);
        $total = mysqli_num_rows($total);
        for ($i = 0; $i < count($data); $i++) {
            if (empty($data[$i]['url'])) {
                $data[$i]['url'] = [];
            } else {
                $data[$i]['url'] = [$data[$i]['url']];
            }

            if ($data[$i]['start_time'] < 10000000) {
                $data[$i]['start_time'] = '';
            } else {
                $data[$i]['start_time'] = date('Y-m-d H:i:s', $data[$i]['start_time']);
            }
            if ($data[$i]['end_time'] < 10000000) {
                $data[$i]['end_time'] = '';
            } else {
                $data[$i]['end_time'] = date('Y-m-d H:i:s', $data[$i]['end_time']);
            }
            $data[$i]['trip_active'] = [];
            $data[$i]['trip_eat'] = [];
        }

//        $active_person_ids = array_column($data, 'id');
//        $active_person_ids = array_unique($active_person_ids);
//        $active_person_ids = implode(',', $active_person_ids);
//        if (!empty($active_person_ids)) {
//            $trip = mysqli_query($con, "select * from active_person_trip where active_person_id in ($active_person_ids) and is_delete=1 and status=1");
//            $trip = mysqli_fetch_all($trip, true);
//            for($i=0; $i<count($trip); $i++) {
//                $trip[$i]['start_time'] = date('Y-m-d H:i:s', $trip[$i]['start_time']);
//                $trip[$i]['end_time'] = date('Y-m-d H:i:s', $trip[$i]['end_time']);
//            }
//            for ($i = 0; $i < count($data); $i++) {
//                for ($o = 0; $o < count($trip); $o++) {
//                    if ($data[$i]['id'] == $trip[$o]['active_person_id']) {
//                        switch ($trip[$o]['type']) {
//                            case '1'://活动行程
//                                $data[$i]['trip_active'][] = $trip[$o];
//                                break;
//                            case '2'://就餐行程
//                                $data[$i]['trip_eat'][] = $trip[$o];
//                                break;
//                        }
//                    }
//                }
//            }
//        }
        mysqli_close($con);
        return out_right([
            'data' => $data,
            'page' => $page,
            'size' => $size,
            'total' => $total,
            'total_page' => ceil($total / $size)
        ]);
    }

    //修改状态
    public function changeStatus($request)
    {
        $id = (int)$request['id'];
        $status = (int)$request['status'];
        $time = time();
        $con = con();
        $res = mysqli_query($con, "update active_person set status=$status,update_time=$time where id=$id");
        mysqli_close($con);
        if ($res) {
            return out_right();
        } else {
            return out_error();
        }
    }

    //获取二维码压缩包
    public function getZip()
    {
        $con = con();
        $data = mysqli_query($con, "select * from active_person where is_delete=1 and status=1");
        $data = mysqli_fetch_all($data, true);
        mysqli_close($con);
        $res = [];
        for ($i = 0; $i < count($data); $i++) {
            if (!empty($data[$i]['url'])) {
                $res[] = [
                    'name' => $data[$i]['name'],
                    'url' => $data[$i]['url']
                ];
            }
        }
        $url = zip::get_url($res);
        if (empty($url)) {
            return out_error('获取失败！');
        } else {
            return out_right($url);
        }

    }

    //表格导入
    public function exportSuperVip($data)
    {
        $time = time();
        $img = $data['file'];
        $active_id = (int)$data['active_id'];
        $file = base64_to_file::getAll("", $img[0]["file_name"], $img[0]["file"], $img[0]['size']);

        $data = readXlsxFile($file['path']);
        array_shift($data);

        $con = con();

        $sql0 = "insert into active_person_trip(active_person_id,type,content,start_time,end_time,create_time,update_time) values";
        $finish_num = 0;
        $total = count($data);
        for ($i = 0; $i < $total; $i++) {

            //插入历史嘉宾信息
            $class = $data[$i][1];
            $org = $data[$i][2];
            $name = $data[$i][3];
            $sex = $data[$i][4];
            $nation = $data[$i][5];
            $job = $data[$i][6];
            $phone = $data[$i][7];
            $num = mysqli_query($con, "select * from guest where name='$name' and class='$class' and org='$org'");
            $num = mysqli_fetch_all($num, true);
            if (count($num) === 0) {//不存在，则执行插入
                mysqli_query($con, "insert into guest(class,org,name,sex,nation,job,phone,create_time,update_time) values('$class','$org','$name','$sex','$nation','$job','$phone',$time,$time )");
                $guest_id = mysqli_insert_id($con);
            } else {//存在，则拿去id
                $guest_id = (int)$num[0]['id'];
            }

            //插入活动人员明细信息
            $start_type = $data[$i][8];
            $start_time = date('Y-m-d', strtotime("1899-12-30 +{$data[$i][9]} days"));
            $end_type = $data[$i][10];
            $end_time = date('Y-m-d', strtotime("1899-12-30 +{$data[$i][11]} days"));;
            $hotel_name = $data[$i][12];
            $hotel_room_type = $data[$i][13];
            $hotel_room = $data[$i][14];
            $driver_name = $data[$i][19];
            $car_no = $data[$i][17];
            $car_officer = $data[$i][18];
            $leader_root = $data[$i][20];
            $leader_org = $data[$i][21];
            $worker = $data[$i][22];
            $remark = $data[$i][23];

//            $trip_active = $this->getTrip($data[$i][15]);
//            $trip_eat = $this->getTrip($data[$i][16]);
            $trip_active = $data[$i][15];
            $trip_eat = $data[$i][16];
            $res = mysqli_query($con, "insert into active_person(active_id,guest_id,start_type,start_time,end_type,end_time,hotel_name,hotel_room_type,hotel_room,driver_name,car_no,car_officer,leader_root,leader_org,worker,create_time,update_time,remark,active,eat) 
                                                        values($active_id,$guest_id,'$start_type',$start_time,'$end_type',$end_time,'$hotel_name','$hotel_room_type','$hotel_room','$driver_name','$car_no','$car_officer','$leader_root','$leader_org','$worker',$time,$time,'$remark','$trip_active','$trip_eat')");

            if ($res) {
                $finish_num += 1;

//                //插入行程信息
//                $active_person_id = mysqli_insert_id($con);
//                if (!empty($trip_active)) {
//                    $a = [];
//                    for ($i = 0; $i < count($trip_active); $i++) {
//                        $content = $trip_active[$i]['content'];
//                        $start_time = strtotime($trip_active[$i]['start_time']);
//                        $end_time = strtotime($trip_active[$i]['end_time']);
//                        $a[] = "($active_person_id,1,'$content',$start_time,$end_time,$time,$time)";
//                    }
//                    $sql = $sql0 . implode(',', $a);
//                    mysqli_query($con, $sql);
//                }
//
//                if (!empty($trip_eat)) {
//                    $a = [];
//                    for ($i = 0; $i < count($trip_eat); $i++) {
//                        $content = $trip_eat[$i]['content'];
//                        $start_time = strtotime($trip_eat[$i]['start_time']);
//                        $end_time = strtotime($trip_eat[$i]['end_time']);
//                        $a[] = "($active_person_id,2,'$content',$start_time,$end_time,$time,$time)";
//                    }
//                    $sql = $sql0 . implode(',', $a);
//                    mysqli_query($con, $sql);
//                }
            }


        }


        mysqli_close($con);

        return out_right("总数据$total 条，导入成功$finish_num 条");
    }

    //将行程字符串提取为数组、对象
    public function getTrip($string)
    {
        $pattern = '/(\d+)\.(\d{4}\/\d{1,2}\/\d{1,2} \d{1,2}:\d{2})—(\d{4}\/\d{1,2}\/\d{1,2} \d{1,2}:\d{2})(.*?)(?=\n\d+\.|\z)/s';
        preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);

        $result = [];
        foreach ($matches as $match) {
            $result[] = [
                'start_time' => trim($match[2]),
                'end_time' => trim($match[3]),
                'content' => trim($match[4])
            ];
        }
        return $result;
    }

    //修改单元格数据
    public function modify($data)
    {
//        var not=[
//            'id',
//            'active_id',
//            'create_time',
//            'delete_time',
//            'guest_id',
//            'is_delete',
//            'status',
//            'trip_active',
//            'trip_eat',
//            'update_time',
//        ];

//        var sex=[
//            'sex'
//        ];
//        var guest=[
//            'class','job','name','nation','org','phone',
//        ];

//        var time=[
//            'start_time',
//            'end_time',
//        ];
//        var text=[
//            'car_no','car_officer','active','driver_name','eat','end_type','hotel_name','hotel_room',
//            'hotel_room_type','leader_org','leader_root','remark','start_type','worker',
//        ];


//        guest：sex、time
//        active_person:time(转成时间戳)、text

        $time = time();
        $id = (int)$data['id'];
        $guest_id = (int)$data['guest_id'];
        $name = $data['name'];
        $value = $data['value'];
        $type = $data['type'];
        switch ($type) {
            case 'not'://非法
                return out_error('非法访问！代码：4021。');
            case 'sex':
                $sql = "update guest set $name='$value',update_time=$time where id=$guest_id";
                break;
            case 'guest':
                $sql = "update guest set $name='$value',update_time=$time where id=$guest_id";
                break;
            case 'time':
                $value = strtotime($value);
                $sql = "update active_person set $name=$value,update_time=$time where id=$id";
                break;
            case 'text':
                $sql = "update active_person set $name='$value',update_time=$time where id=$id";
                break;
        }
        $con = con();
        $res = mysqli_query($con, $sql);
        mysqli_close($con);
        if ($res) {
            return out_right();
        } else {
            return out_error('修改失败！');
        }


    }

    //保存行程权限数据
    public function savePower($data)
    {
        $power = $data['power'];
        $power = json_encode($power);
        $con = con();
        $res = mysqli_query($con, "update setting set value_1='$power' where id=11");
        mysqli_close($con);
        if ($res) {
            return out_right('保存成功！');
        } else {
            return out_error('保存失败！');
        }
    }

    //批量删除
    public function delAll($data)
    {
        $ids = $data['ids'];
        if (empty($ids)) {
            return out_error('请选择要删除的数据！');
        }
        $ids = implode(',', $ids);
        $time = time();
        $con = con();
        $res = mysqli_query($con, "update active_person set is_delete=0,delete_time=$time where id in ($ids)");
        mysqli_close($con);
        if ($res) {
            return out_right('删除成功！');
        } else {
            return out_error('删除失败！');
        }
    }

}